package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.constant.RedisConstant;
import com.itheima.dao.SetmealDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.Setmeal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import redis.clients.jedis.JedisPool;

import java.util.List;


@Service(interfaceClass = SetmealService.class)
@Transactional
public class SetmealServiceImpl implements SetmealService {
    @Autowired
    private SetmealDao setmealDao;
    @Autowired
    private JedisPool jedisPool;
    @Override
    public void add(Setmeal setmeal, Integer[] checkgroupIds) {
        //添加套餐
        setmealDao.add(setmeal);
        Integer setmealId = setmeal.getId();
        //绑定套餐和检查组的多对多关系
        if (checkgroupIds!=null&&checkgroupIds.length>0) {
            for (Integer checkgroupId : checkgroupIds) {
                setmealDao.addSetmealandCheckgroup(setmealId,checkgroupId);
            }
        }
        //储存和表单信息一起提交的图片名称
        String fileName = setmeal.getImg();
        jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES,fileName);
    }

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        String queryString = queryPageBean.getQueryString();
        PageHelper.startPage(queryPageBean.getCurrentPage(),queryPageBean.getPageSize());
        Page<Setmeal> page = setmealDao.queryPage(queryString);

        return new PageResult(page.getTotal(),page.getResult());
    }

    @Override
    public Setmeal findById(Integer id) {
        return setmealDao.findById(id);
    }

    @Override
    public void delete(Integer id) {
        long count = setmealDao.findCheckgroupidbysetmealid(id);
        if (count>0){
          throw new RuntimeException("当前套餐存在关联项，删除失败");
        }else{
            setmealDao.delete(id);
        }
    }

    @Override
    public void update(Setmeal setmeal,Integer[] checkgroupIds) {
        setmealDao.update(setmeal);
        setmealDao.deleteAssoicationsetmealid(setmeal.getId());
        Integer setmealId = setmeal.getId();
        for (Integer checkgroupId : checkgroupIds) {
            setmealDao.addSetmealandCheckgroup(setmealId,checkgroupId);
        }
    }

    @Override
    public List<Integer> findcheckgroupIds(Integer setmealId) {
        return setmealDao.findcheckgroupIds(setmealId);
    }
}
